package org.nanhill.moo.web.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.nanhill.commons.model.pagination.Pagination;
import org.nanhill.moo.domain.Cost;
import org.nanhill.moo.domain.Favor;
import org.nanhill.moo.service.CostService;
import org.nanhill.moo.service.FavorService;
import org.nanhill.moo.web.form.PageFavorForm;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author alin [xalinx at gmail dot com]
 * @date 2006-9-15
 */
public class ShowFavorController extends NamedFormController {
	private static final String FORM_NAME = "showFavorForm";

	private CostService costService;

	public void setCostService(CostService costService) {
		this.costService = costService;
	}

	private FavorService favorService;

	public void setFavorService(FavorService favorService) {
		this.favorService = favorService;
	}

	public ShowFavorController() {
		this.setCommandClass(PageFavorForm.class);
		this.setCommandName(FORM_NAME);
		this.setSubmitType(FORM_NAME);
	}

	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Object command = getCommand(request);
		bindAndValidate(request, command);
		return onSubmit(request, response, command, null);
	}

	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		PageFavorForm form = (PageFavorForm) command;

		// 得到Favor分页,包含页码
		Pagination<Favor> favorPage = this.favorService.loadPageLatest(form
				.getPageId(), form.getPageSize(), form.getCostId(), form
				.getUserId(), form.getCategoryId());
		// 得到cost集合，包含每个cost的favor数
		Cost[] costs = costService.loadAllWithFavorCount();

		// --- 生成显示模型
		Map<String, Object> viewModel = new HashMap<String, Object>();
		viewModel.put("costs", costs);
		viewModel.put("userId", form.getUserId());
		viewModel.put("costId", form.getCostId());
		viewModel.put("categoryId", form.getCategoryId());
		viewModel.put("favorPage", favorPage);
		// ---

		return new ModelAndView(this.getSuccessView(), viewModel);
	}
}